/**
 * Copyright (c) qzsoft All rights reserved.
 * <p>
 * qzsoft.cn
 * <p>
 * 版权所有，侵权必究！
 */

package com.qzsoft.system.modules.sys.notice.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qzsoft.jeemis.common.constant.Constant;
import com.qzsoft.jeemis.common.exception.RenException;
import com.qzsoft.jeemis.common.service.BaseService;
import com.qzsoft.jeemis.common.utils.ConvertDictUtils;
import com.qzsoft.jeemis.platform.security.user.UserDetail;
import com.qzsoft.system.modules.permission.dept.dao.SysDeptMapper;
import com.qzsoft.system.modules.sys.notice.dao.SysNoticeDao;
import com.qzsoft.system.modules.sys.notice.dao.SysNoticeFileDao;
import com.qzsoft.system.modules.sys.notice.dao.SysNoticeUserMapper;
import com.qzsoft.system.modules.sys.notice.dto.SysNoticeDto;
import com.qzsoft.system.modules.sys.notice.entity.SysNoticeEntity;
import com.qzsoft.system.modules.sys.notice.entity.SysNoticeFileEntity;
import com.qzsoft.system.modules.sys.notice.entity.SysNoticeUserEntity;
import com.qzsoft.system.modules.sys.notice.service.SysNoticeService;
import com.qzsoft.system.modules.sys.noticeTemplate.common.TemplateUtils;
import com.qzsoft.system.repository.sys.dao.SysUserDao;
import com.qzsoft.system.repository.sys.entity.SysDeptEntity;
import com.qzsoft.system.repository.sys.entity.SysUserEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Predicate;

/**
 * 系统用户
 *
 * @author
 */
@Service
public class SysNoticeServiceImpl extends BaseService implements SysNoticeService {

    @Autowired
    private SysNoticeDao sysNoticeDao;
    @Autowired
    private SysNoticeFileDao sysNoticeFileDao;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysNoticeUserMapper sysNoticeUserMapper;

    @Autowired
    private SysUserDao sysUserDao;

    @Override
    public IPage<SysNoticeEntity> page(Map<String, Object> params) {
        IPage<SysNoticeEntity> page = this.getPage(params, Constant.CREATE_DATE, false, SysNoticeEntity.class);
        QueryWrapper<SysNoticeEntity> queryWrapper = this.getQueryWrapper(params, SysNoticeEntity.class, "title");
        IPage<SysNoticeEntity> pageData = sysNoticeDao.selectPage(page, queryWrapper);
        pageData = ConvertDictUtils.formatDicDataPage(pageData);
        return pageData;
    }

    @Override
    public List<SysNoticeEntity> list(Map<String, Object> params) {
        QueryWrapper<SysNoticeEntity> queryWrapper = this.getQueryWrapper(params, SysNoticeEntity.class, "title");
        List<SysNoticeEntity> entityList = sysNoticeDao.selectList(queryWrapper);
        entityList = ConvertDictUtils.formatDicDataList(entityList);
        return entityList;
    }

    @Override
    public SysNoticeEntity get(String id) {
        SysNoticeEntity entity = sysNoticeDao.selectById(id);
        QueryWrapper<SysNoticeFileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("notice_id", id).orderByAsc("orderid", "create_date");
        List<SysNoticeFileEntity> fileEntityList = sysNoticeFileDao.selectList(queryWrapper);
        entity = ConvertDictUtils.formatDicData(entity);
        entity.setFileList(fileEntityList);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(SysNoticeEntity entity) {
        entity.setId(IdWorker.get32UUID());
        if (entity.getOrderid() == null) {
            entity.setOrderid(1);
        }
        /***************  2020-10-10 16:20:00  添加通知发送失败异常处理  孙广强  ADD START  ***************/
        try {
            if (MapUtil.isNotEmpty(entity.getTemplateVars())) {
                entity.setContent(TemplateUtils.replace(entity.getContent(), entity.getTemplateVars()));
            }
        } catch (Exception e) {
            throw new RenException("通知发送失败！");
        }
        /***************  2020-10-10 16:20:00  添加通知发送失败异常处理  孙广强  ADD END  ***************/
        // yanguoqing update
        // entity.setDeptPkid(this.basegetLoginUser().getDeptPkid());
        sysNoticeDao.insert(entity);
        // 保存附件
        this.saveNoticeFiles(entity);
    }

    /**
     * 保存附件
     *
     * @param entity
     */
    private void saveNoticeFiles(SysNoticeEntity entity) {
        QueryWrapper<SysNoticeFileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("notice_id", entity.getId());
        sysNoticeFileDao.delete(queryWrapper);
        List<SysNoticeFileEntity> fileEntityList = entity.getFileList();
        int i = 1;
        for (SysNoticeFileEntity fileEntity : fileEntityList) {
            fileEntity.setId(IdWorker.get32UUID());
            fileEntity.setNoticeId(entity.getId());
            fileEntity.setOrderid(i++);
            fileEntity.setFileType(FileUtil.extName(fileEntity.getFileName()).toLowerCase());
            sysNoticeFileDao.insert(fileEntity);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysNoticeEntity entity) {
        sysNoticeDao.updateById(entity);
        // 保存附件
        this.saveNoticeFiles(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String[] ids) {
        //删除通知
        sysNoticeDao.deleteBatchIds(Arrays.asList(ids));
        // 删除附件
        QueryWrapper<SysNoticeFileEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("notice_id", ids);
        sysNoticeFileDao.delete(queryWrapper);
        /***************  2020-10-10 16:30:00  新增关联表更新  孙广强  ADD START  ***************/
        // 关联表更新（sys_notice_user）
        UpdateWrapper<SysNoticeUserEntity> updateNoticeUser = new UpdateWrapper<>();
        updateNoticeUser.set("has_delete", 1).in("notice_id", ids);
        sysNoticeUserMapper.update(new SysNoticeUserEntity(), updateNoticeUser);
        /***************  2020-10-10 16:30:00  新增关联表更新  孙广强  ADD END  ***************/
    }

    /***************  2020-10-10 16:30:00  修改发布公告  孙广强  UPDATE START  ***************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String publishStart(SysNoticeEntity entity) {
        String result = "";
        // 发布的时候关联表插入数据
        UserDetail userDetail = this.basegetLoginUser();
        // 根据用户ID查询用户详情
        SysUserEntity SysUserInfo = sysUserDao.selectById(userDetail.getId());
        if (StringUtils.isEmpty(SysUserInfo.getDeptId())) {
            return "系统用户不能发布通知";
        }

        UpdateWrapper<SysNoticeEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("publish_date", new Date());
        updateWrapper.set("has_publish", 1).eq("id", entity.getId());
        sysNoticeDao.update(new SysNoticeEntity(), updateWrapper);

        // 根据登录用户ID获取用户机构信息
        SysDeptEntity sysDeptEntityUser = deptMapper.selectById(SysUserInfo.getDeptPkid());
		if (sysDeptEntityUser == null) {
            return "当前机构信息为空";
        }
        QueryWrapper<SysNoticeUserEntity> queryWrapper = Wrappers.query();

        Predicate<Object> isEmpty = obj -> Objects.isNull(obj) || StringUtils.isBlank(String.valueOf(obj));
        // 通告范围 1 全员
        if ("1".equals(entity.getNoticeScope())) {
            queryWrapper.likeRight(!isEmpty.test(sysDeptEntityUser.getId()), "id", sysDeptEntityUser.getId());
            // 通告范围 2 所有下级单位
        } else if ("2".equals(entity.getNoticeScope())) {
            queryWrapper.likeRight(!isEmpty.test(sysDeptEntityUser.getId()), "id", sysDeptEntityUser.getId())
                    .ne(!isEmpty.test(sysDeptEntityUser.getId()), "id", sysDeptEntityUser.getId());
            // 通告范围 3直属单位
        } else if ("3".equals(entity.getNoticeScope())) {
            queryWrapper.eq(!isEmpty.test(sysDeptEntityUser.getId()), "pid", sysDeptEntityUser.getId());
        }
        List<SysNoticeUserEntity> sysNoticeUserEntityList = sysNoticeUserMapper.getUserList(queryWrapper);
        if (sysNoticeUserEntityList != null && sysNoticeUserEntityList.size() > 0) {
            SysNoticeUserEntity SysNoticeUserEntityTemp = null;
            for (int i = 0; i < sysNoticeUserEntityList.size(); i++) {
                SysNoticeUserEntityTemp = sysNoticeUserEntityList.get(i);
                SysNoticeUserEntityTemp.setId(IdWorker.get32UUID());
                SysNoticeUserEntityTemp.setNoticeId(entity.getId());
                SysNoticeUserEntityTemp.setReadFlag(false);
                SysNoticeUserEntityTemp.setHasDelete(0);
                // 创建者
                SysNoticeUserEntityTemp.setCreator(userDetail.getId());
                // 创建时间
                SysNoticeUserEntityTemp.setCreateDate(new Date());
            }
            QueryWrapper<SysNoticeUserEntity> queryWrapperDelete = new QueryWrapper<>();
            queryWrapperDelete.eq("notice_id", entity.getId());
            sysNoticeUserMapper.delete(queryWrapperDelete);
            sysNoticeUserMapper.insertBatchNoticeUser(sysNoticeUserEntityList);
        }
        return result;
    }
    /***************  2020-10-10 16:30:00  修改发布公告  孙广强  UPDATE END  ***************/

    /***************  2020-10-10 16:30:00  修改停止发布公告  孙广强  UPDATE START  ***************/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publishStop(SysNoticeEntity entity) {
        UpdateWrapper<SysNoticeEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("has_publish", 0).eq("id", entity.getId());
        sysNoticeDao.update(new SysNoticeEntity(), updateWrapper);
        // 关联表更新（sys_notice_user）
        UpdateWrapper<SysNoticeUserEntity> updateNoticeUser = new UpdateWrapper<>();
        updateNoticeUser.set("has_delete", 1).eq("notice_id", entity.getId());
        sysNoticeUserMapper.update(new SysNoticeUserEntity(), updateNoticeUser);
    }
    /***************  2020-10-10 16:30:00  修改停止发布公告  孙广强  UPDATE END  ***************/

    /***************  2020-10-10 16:40:00  新增公告处理方法  孙广强  ADD START  ***************/
    @Override
    public List<SysNoticeDto> getNoticeList(SysNoticeDto dto) {
        UserDetail userDetail = this.basegetLoginUser();
        dto.setUserId(userDetail.getId().toString());
        List<SysNoticeDto> result = sysNoticeUserMapper.getNoticeList(dto);
        return result;
    }

    @Override
    public int selectNotReadNoticeCount(SysNoticeDto dto) {
        UserDetail userDetail = this.basegetLoginUser();
        dto.setUserId(userDetail.getId().toString());
        int cnt = sysNoticeUserMapper.getNotReadCount(dto);
        return cnt;
    }

    @Override
    public IPage<SysNoticeDto> getNoticeListByPage(Page page, SysNoticeDto dto) {
        UserDetail userDetail = this.basegetLoginUser();
        dto.setUserId(userDetail.getId().toString());
        IPage<SysNoticeDto> pageData = sysNoticeUserMapper.getNoticeListByPage(page, dto);
        return pageData;
    }
    /***************  2020-10-10 16:40:00  新增公告处理方法  孙广强  ADD END  ***************/

}
